<?php
declare (strict_types=1);

namespace app\exam\service\admin;

use app\common\logic\category\admin\Category;
use app\common\service\BaseService;
use app\course\logic\base\Course;
use app\exam\logic\admin\QuestionBank as QuestionBankLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use Exception;
use think\annotation\Inject;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

/**
 * 题库-后台
 */
class QuestionBank extends BaseService
{

    /**
     * @Inject()
     *
     * @var QuestionBankLogic
     */
    protected $questionBankLogic;

    /**
     * @Inject()
     *
     * @var Category
     */
    protected $category;

    /**
     * 分类顶级数据列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @return mixed
     * @throws DbException
     */
    public function index()
    {
        // 搜索功能
        $map = [];
        Request::has('title', 'get', true) && $map[] = ['title', 'like', '%' . Request::get('title/s') . '%'];
        // 分类
        $category = Request::get('category/d', 0);
        $category && $map[] = ['category', 'like', '%,' . $category . ',%'];
        // 状态
        if (Request::has('status', 'get', true) && Request::get('status/d', -1) !== -1) {
            $map[] = ['status', '=', Request::get('status/d')];
        } else {
            $map[] = ['status', 'in', '0,1'];
        }
        $data = $this->questionBankLogic->getList($map);
        // 定义字段
        $keyList = [
            'title'        => ListItem::make()->title('题库名称'),
            'category_str' => ListItem::make()->title('所属分类'),
            'status'       => ListItem::make('custom')->title('启用状态'),
            // 'open'      => ListItem::make('custom')->title('是否公开'),
            'num'          => ListItem::make()->title('题目数量'),
            'user_name'    => ListItem::make()->title('创建人'),
            'update_time'  => ListItem::make()->title('更新时间')
        ];

        $category  = $this->category->cascader(0, 3);
        $searchKey = [
            'title'    => FormItem::make('input')->title(false)->placeholder('名称')->maxlength(30),
            'category' => FormItem::make('cascader')->title(false)->options($category)->placeholder('分类')->required(),
            'status'   => FormItem::make('select')->title(false)->placeholder('状态')->options([
                ['title' => '不限制', 'value' => -1],
                ['title' => '正常', 'value' => 1],
                ['title' => '禁止', 'value' => 0],
            ]),
        ];

        // 设置表单
        $list = new PageList;
        // 表单字段
        $list->pageKey   = $keyList;
        $list->datas     = $data;
        $list->searchKey = $searchKey;

        return $list->send();
    }

    /**
     * 创建题库
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @return Response
     */
    public function create()
    {
        if (Request::isPost()) {
            $data = Request::post();
            $this->questionBankLogic->createQuestionBank($data);

            return $this->parseToData([], 1, '新建成功');
        }
        /* 创建课程界面配置 */
        $keyList = $this->keyListInit();
        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->pageKey = $keyList;

        $form->saveMethod  = 'POST';
        $form->savePostUrl = '/exam/admin/question/bank/create';

        return $form->send();

    }

    /**
     * 编辑题库
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @param int $id
     * @return Response
     */
    public function update(int $id)
    {
        if (Request::isPut()) {
            $data = Request::put();
            $this->questionBankLogic->editQuestionBank($id, $data);

            return $this->parseToData([], 1, '编辑成功');
        }

        $data        = $this->questionBankLogic->findOrFail($id);
        $data->cates = $data->fullcategorypath;
        // 创建课程界面配置
        $keyList = $this->keyListInit(!!$data->num);
        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->datas       = $data;
        $form->pageKey     = $keyList;
        $form->saveMethod  = 'PUT';
        $form->savePostUrl = '/exam/admin/question/bank/' . $id . '/edit';

        return $form->send();
    }

    /**
     * 表单字段
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @param bool $disabled
     * @return array
     */
    public function keyListInit($disabled = false)
    {
        // 题库分类
        $category = $this->category->cascader(0, 3);
        // 定义字段
        return [
            'title' => FormItem::make()->title('名称')->required(),
            'cates' => FormItem::make('cascader')->title('分类')->options($category)->required()->disabled($disabled),
            // 'open'  => FormItem::make('slideSwitch')->title('是否公开')->activeValue(1)->inactiveValue(0)->help('公开后，该题库可供其他人员使用'),
        ];
    }

    /**
     * 编辑字段
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @param int $id
     * @param     $field
     * @return Response
     */
    public function editField(int $id, $field)
    {
        $value = Request::put($field);
        $this->questionBankLogic->editField($id, $field, $value);

        return $this->parseToData([], 1, '更新成功');
    }

    /**
     * 删除题库
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/29
     *
     * @param int $id
     * @return Response
     */
    public function delete(int $id)
    {

        $this->questionBankLogic->deleteQuestionBank($id);

        return $this->parseToData([], 1, '删除成功');
    }

    /**
     * 题库选择面板
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/11/23
     *
     * @return Response
     */
    public function choose()
    {
        // 默认当前请求的机构
        $mhmId = request()->mhm_id;

        if (Request::has('data_id', 'get', true)) {
            $courseId = Request::get('data_id/d');
            switch (Request::get('data_type/s')) {
                case 'video':
                    $mhmId = Course::where('id', $courseId)->value('mhm_id');
                    break;
                default:
                    $mhmId = 0;
            }

        }

        // 题库分类
        $category = $this->category->cascader(0, 3, $mhmId);
        // 启用状态
        $status = $this->questionBankLogic->getStatusOptions();

        return $this->parseToData(
            [
                'category' => $category,
                'status'   => $status
            ],
            1
        );
    }

    /**
     * 获取题库选择的列表数据
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/11/23
     *
     * @return Response
     * @throws DbException
     */
    public function getChooseList()
    {
        $map = [];
        Request::has('title', 'get', true) && $map[] = ['title', 'like', '%' . Request::get('title/s') . '%'];

        $category = Request::get('category/s', '');
        $category && $map[] = ['category', 'like', '%,' . $category . ',%'];

        if (Request::has('status', 'get', true) && Request::get('status/d', -1) !== -1) {
            $map[] = ['status', '=', Request::get('status/d')];
        } else {
            // 搜索功能
            $map[] = ['status', 'in', '0,1'];
        }

        // 默认当前请求的机构
        $mhmId = request()->mhm_id;

        if (Request::has('data_id', 'get', true)) {
            $courseId = Request::get('data_id/d');
            switch (Request::get('data_type/s')) {
                case 'video':
                    $mhmId = Course::where('id', $courseId)->value('mhm_id');
                    break;
                default:
                    $mhmId = 0;
            }

        }

        $datas = $this->questionBankLogic->getChooseList($map, $mhmId);

        $list        = new PageList();
        $list->datas = $datas;

        return $list->send();
    }

    /**
     * 搜索题库
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/3/12
     *
     * @return Response
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function search()
    {
        $keyword = Request::get('keyword/s', '');
        $list    = $this->questionBankLogic->searchBank($keyword);

        return $this->parseToData($list, 1);
    }

    /**
     * 批量禁用题库
     *
     * @return Response
     * @throws Exception
     */
    public function disables()
    {
        $ids = Request::put('ids/a');

        $this->questionBankLogic->batchUpdated($ids, 'status', 0);

        return $this->parseToData([], 1, '禁用成功');
    }

    /**
     * 批量启用题库
     *
     * @return Response
     */
    public function enables()
    {
        $ids = Request::put('ids/a');

        $this->questionBankLogic->batchUpdated($ids, 'status', 1);

        return $this->parseToData([], 1, '启用成功');
    }

}
